package com.felix.datasources.aspect;

import com.felix.datasources.DataSourceNames;
import com.felix.datasources.DynamicDataSource;
import com.felix.datasources.annotation.DataSource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 多数据源，切面处理类
 *
 * @author xuejinhua
 * @date 2017/9/16 22:20
 */
@Slf4j
@Aspect
@Component
@Order(1)
public class DataSourceAspect {
    //@within在类上设置
    //@annotation在方法上进行设置
    @Pointcut("@annotation(com.felix.datasources.annotation.DataSource)")
    public void dataSourcePointCut() {
    }

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Method method = ((MethodSignature) point.getSignature()).getMethod();
        DataSource dataSource = method.getAnnotation(DataSource.class);
        if (dataSource == null) {
            DynamicDataSource.setDataSource(DataSourceNames.MASTER);
            log.debug("set datasource is " + DataSourceNames.MASTER);
        } else {
            //获取注解上的数据源的值的信息
            DynamicDataSource.setDataSource(dataSource.name());
            log.debug("set datasource is " + dataSource.name());
        }
        try {
            return point.proceed();
        } finally {
            DynamicDataSource.clearDataSource();
            log.debug("clean datasource");
        }
    }

}
